#pragma once

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <cstring>
#include <string>

#include "Log.hpp"

using namespace MyLogModule;
const uint16_t g_port = 8080;
const std::string g_ip = "127.0.0.1";

class TcpClient
{
public:
    TcpClient(uint16_t port = g_port,std::string ip = g_ip)
        :_port(port)
        ,_ip(ip)
    {}
    ~TcpClient()
    {}

    void Start()
    {
        _socket = ::socket(AF_INET,SOCK_STREAM,0);
        if(_socket < 0)
        {
            LOG(FATAL) << "Client create socket fail";
            return;
        }
        sockaddr_in local;
        memset(&local,sizeof(local),0);
        socklen_t len = sizeof(local);
        local.sin_family = AF_INET;
        local.sin_port = ::htons(_port);
        // local.sin_addr.s_addr = ::inet_addr(_ip.c_str());
        ::inet_pton(AF_INET,_ip.c_str(),&local.sin_addr);

        //必须要有 Ip 和 Port, 需要bind， 但是不需要用户显示的bind， client系统随机绑定端口

        int n = ::connect(_socket,(sockaddr*)&local,len);
        if(n < 0)
        {
            LOG(FATAL) << "connect fail";
            return;
        }

        while(true)
        {
            std::string message;
            std::cout << "Pleast enter#";
            std::getline(std::cin,message);
            int num = ::write(_socket,message.c_str(),message.size());
            if(num > 0)
            {
                char buffer[1024];
                int n = ::read(_socket,buffer,sizeof(buffer)-1);
                if(n > 0)
                {
                    buffer[n] = 0;
                    std::cout << buffer << std::endl;
                }
                else
                    break;
            }
            else
            {
                break;
            }
        }
    }
private:
    int _socket;
    uint16_t _port;
    std::string _ip;
};
